package com.zlcx.tz.live.processor.impl;

import com.zlcx.tz.live.client.SocketClient;
import com.zlcx.tz.live.client.UserClient;
import com.zlcx.tz.live.processor.SitUpPostProcessor;
import com.zlcx.tz.live.service.impl.UserService;
import com.zlcx.tz.live.vo.ShareMsgParamVO;
import com.zlcx.tz.live.vo.TimeLearnRoomSeatsDTO;
import com.zlcx.tz.live.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.core.task.AsyncTaskExecutor;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.List;
import static com.zlcx.tz.live.enums.MessageType.TIME_LEARN_ROOM_SIT_UP;
import static com.zlcx.tz.live.enums.MessageType.TIME_LEARN_ROOM_SIT_UP_NOTICE;

/**
 * @author: anjl
 * @description: （异步）更新计时自习室房间信息->房间总座位数和房间空余座位数
 * @data: 2020-09-27
 **/
@Slf4j
@Order(100)
@Component
public class SitUpMessagePostProcessor implements SitUpPostProcessor<TimeLearnRoomSeatsDTO> {

    @Override
    public void processor(TimeLearnRoomSeatsDTO seat) {
        Asserts.notNull(seat, "seat is null !");
        UserVO userInfo = userService.getUserInfo(seat.getUserId());

        asyncTaskExecutor.execute(() -> {

            ShareMsgParamVO msg = buildMessage(TIME_LEARN_ROOM_SIT_UP.getCode(), seat, userInfo.getName(), seat.getRoomId().toString());
            socketClient.sendMsg(msg);
            log.info("计时房间操作-用户结束学习 msg = {}", msg);
        });

        //使用不同线程池，是优先级不同，做隔离
        commonExecutor.execute(() -> {
            List<UserVO> friends = userClient.findOnlineFriends(seat.getUserId()).getData();
            friends.forEach(user -> {
                ShareMsgParamVO msg = buildMessage(TIME_LEARN_ROOM_SIT_UP_NOTICE.getCode(), seat, userInfo.getName(), user.getId().toString());
                socketClient.sendMsg(msg);
                log.info("计时房间操作-好友通知-用户开始学习 msg = {}", msg);
            });

        });
    }

    private ShareMsgParamVO buildMessage(String messageType, TimeLearnRoomSeatsDTO seat, String fromUserName, String toId) {
        return ShareMsgParamVO
                .builder()
                .type(messageType)
                .message(fromUserName + "结束学习")
                .toId(toId)
                .fromUserId(seat.getUserId().toString())
                .contentId(seat.getRoomId().toString())
                .build();
    }

    @Autowired
    private UserClient userClient;
    @Autowired
    private SocketClient socketClient;
    @Autowired
    private UserService userService;
    @Resource(name = "taskExecutor")
    AsyncTaskExecutor asyncTaskExecutor;
    @Resource(name = "commonExecutor")
    AsyncTaskExecutor commonExecutor;


}
